package com.eras.shoes.utils

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.util.Log
import java.io.IOException
import java.util.UUID


class BluetoothService(private val context: Context) {
    private var bluetoothSocket: BluetoothSocket? = null
    private val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")

    @SuppressLint("MissingPermission")
    fun connectDevice(device: BluetoothDevice): Boolean {
        try {
            bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid)
            bluetoothSocket?.connect()
            return true
        } catch (e: IOException) {
            Log.e("Bluetooth", "连接失败", e)
            return false
        }
    }

    fun writeSerialNumber(serial: String): Boolean {
        return try {
            val bytes = serial.toByteArray(Charsets.UTF_8)
            bluetoothSocket?.outputStream?.write(bytes)
            true
        } catch (e: Exception) {
            Log.e("Bluetooth", "写入失败", e)
            false
        }
    }

    fun disconnect() {
        bluetoothSocket?.close()
    }
}
